import { PageType } from '@/pages/user/data';
import create from 'zustand';
import { persist } from 'zustand/middleware';
import { UserPermission } from './user';

export type MenuInfo = {
  key: string;
  name: string;
  children?: MenuInfo[];
  target: string;
};

export interface MenuStore {
  routes: string[];
  navigations: MenuInfo[];
  buttonMap: Record<string, string[]>;
  collapsed: boolean;
  setPermissions: (permissionList: UserPermission[]) => void;
  setCollapsed: (collapsed: boolean) => void;
}

const fixPermission = (permissionList: UserPermission[], buttonMap: Record<string, string[]>) => {
  const routes: string[] = [];
  const navs: MenuInfo[] = [];
  permissionList.forEach((i) => {
    const nav: MenuInfo = {
      key: i.router,
      name: i.label,
      target: i.actionUrl,
      children: undefined
    };
    if (i.permissionTreeVOList && i.permissionTreeVOList.length > 0) {
      if (i.type === PageType.enum.菜单) {
        const child = fixPermission(i.permissionTreeVOList, buttonMap);
        routes.push(...child.routes);
        nav.children = child.navs;
      }
    } else {
      buttonMap[i.actionUrl] = (i.operationsList ?? []).map((i) => i.router);
    }
    routes.push(i.router);
    navs.push(nav);
  });
  return { routes, navs };
};
/**
 * 菜单数据 store
 */
const useMenuStore = create<MenuStore>(
  persist(
    (set) => ({
      routes: [],
      navigations: [],
      buttonMap: {},
      collapsed: false,
      setPermissions(permissionList) {
        const buttonMap: Record<string, string[]> = {};
        const { routes, navs } = fixPermission(permissionList, buttonMap);
        set({
          routes,
          navigations: [
            { key: 'index', name: '首页', target: '/' },
            {
              target: '/monitor',
              key: 'monitor',
              name: '监控中心',
              children: [
                {
                  target: '/monitor/index',
                  key: 'monitorIndex',

                  name: '雷达地图'
                }
              ]
            },
            ...navs
          ],
          buttonMap
        });
      },
      setCollapsed(collapsed) {
        set({ collapsed });
      }
    }),
    { name: 'menu' }
  )
);
export default useMenuStore;
